<template>
  <h1>购物车</h1>
  <table>
    <tr>
        <td>序号</td>
        <td>商品名称</td>
        <td>商品价格</td>
        <td>数量</td>
        <td>小计</td>
        <td>操作</td>
    </tr>
    <tr v-for="(item,index) in state.shopcartList" :key="item.id">
        <td>
            <input type="checkbox" :checked="item.checked" @change="checkedItem(index)">
        </td>
        <td>{{item.name}}</td>
        <td>{{item.price}}</td>
        <td>
            <button @click="changeNum(index,'decrease')">-</button>
            {{item.num}}
            <button @click="changeNum(index,'increment')">+</button>
        </td>
        <td>{{item.num*item.price}}</td>
        <td>
            <button @click="deleteShopCart(index)">删除</button>
        </td>
    </tr>
    <tr>
        <td colspan="6">
           总价：{{total}}
             总价：{{total}}
               总价：{{total}}
                 总价：{{total}}
        </td>
    </tr>
  </table>
</template>

<script>
import {reactive,computed} from 'vue'
export default {
    setup(){
        const state=reactive({
            shopcartList:[
                {
                    id:'1001',
                    name:'红富士苹果',
                    price:3,
                    num:1,
                    checked:true
                },
                 {
                    id:'1002',
                    name:'草滩西瓜',
                    price:4,
                    num:2,
                    checked:false
                },
                 {
                    id:'1001',
                    name:'周至迷糊桃',
                    price:2,
                    num:3,
                    checked:true
                }
            ]
        })
        
        const changeNum=(index,flag)=>{
            switch(flag){
                case 'increment':
                    state.shopcartList[index].num++
                    break;
                case 'decrease':
                    state.shopcartList[index].num--
                    break;
            }
        }
        const deleteShopCart=index=>{
            state.shopcartList.splice(index,1)
        }
        const checkedItem=index=>{
           state.shopcartList[index].checked=!state.shopcartList[index].checked
        }
        //计算属性
        let total=computed(()=>{
            console.log('--------计算总价-----------');
            return state.shopcartList.filter(item=>item.checked).reduce((pre,cur)=>pre+cur.price*cur.num,0)
        })

        return{state,changeNum,deleteShopCart,checkedItem,total}
    }
}
</script>
<style>
    table{
        border-collapse: collapse;
        width: 500px;
    }
    td{
        border: 1px solid #ccc;
        text-align: center;
        padding: 5px;

    }
</style>